package com.lovo.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.stock.bean.PageInfo;
import com.lovo.stock.bean.PurchaseBean;
import com.lovo.stock.bean.PurdetailBean;
import com.lovo.stock.mapper.PurcartMapper;
import com.lovo.stock.mapper.PurchaseMapper;
import com.lovo.stock.service.IPurchaseService;
import com.lovo.stock.service.IPurdetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, PurchaseBean> implements IPurchaseService {
    @Autowired
    PurchaseMapper purchaseMapper;
    @Autowired
    IPurdetailService purdetailService;


    @Override
    public IPage<PurchaseBean> queryPurchaseByPage(PageInfo<PurchaseBean> pageInfo) {
        //根据供应商名，起始日期，结束日期查询
        QueryWrapper q=new QueryWrapper<>();
        if (pageInfo.getStartTime()!=null&&!"".equals(pageInfo.getStartTime())){
            q.ge("purchase_date",pageInfo.getStartTime());
        }
        if (pageInfo.getEndTime()!=null&&!"".equals(pageInfo.getEndTime())){
            q.le("purchase_date",pageInfo.getEndTime());
        }
        if (pageInfo.getData()!=null){
            q.like("purchase_supplier_name",pageInfo.getData().getPurchaseSupplierName());
        }
        IPage<PurchaseBean> page=purchaseMapper.selectPage(new Page<>(pageInfo.getCurPage(),pageInfo.getPageSize()),q);
        return page;
    }

    @Override
    public PurchaseBean queryPurchaseAndDetailById(int id) {
        //根据id查询出采购信息
        PurchaseBean purchaseBean=purchaseMapper.selectById(id);
        //查询出关联的采购明细表的信息
        List<PurdetailBean> purdetailList=purdetailService.queryPurdetailById(id);
        //将明细表填入采购信息
        purchaseBean.setPurdetails(purdetailList);
        //返回对象
        return purchaseBean;
    }

    @Override
    @Transactional
    public int addPurchase(PurchaseBean purchaseBean) {
        //将采购信息加入数据库,同时返回生成的key值
        purchaseMapper.insert(purchaseBean);
        int purchaseId=purchaseBean.getPurchaseId();
        return purchaseId;
    }
}
